package ajax.servlet;

import ajax.entity.User;
import ajax.service.UserService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckUserServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收ajax提交的数据
        String uname = req.getParameter("uname");
        System.out.println("uname="+uname);

        //使用数据库
        resp.setContentType("text/html;charset=utf-8");
        //如果有就返回user对象，否则，返回的是null
        User userByName = userService.getUserByName(uname);
        if (userByName != null){//说明用户名存在..,返回该user的json格式数据字符串
            String strUser = new Gson().toJson(userByName);
            resp.getWriter().write(strUser);
        }else {
            resp.getWriter().write("");
        }

//        //假定用户名为 king , 就不可用, 其它用户名可以
//        if("king".equals(uname)){
//            //后面这个信息，是从DB获取
//            User king = new User(1, "king", "666", "king@sohu.com");
//            //把 king 转成 json字符串
//            String strKing = new Gson().toJson(king);
//            //返回
//            resp.getWriter().write(strKing);
//        }else {
//            //如果用户名可以用，返回""
//            resp.getWriter().write("");
//        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}